<?php

namespace App\Kuafu\CouponExt\Channel\DouYin;

use App\Kuafu\Config\Model\ConfigModel;
use App\Kuafu\CouponExt\Channel\CouponExtBase;
use App\Kuafu\CouponExt\Channel\CouponExtInterface;
use App\Kuafu\CouponExt\Channel\CouponExtFuncTraits;
use App\Kuafu\CouponExt\Enum\CouponExtEnum;
use App\Kuafu\CouponExt\Exceptions\CouponExtException;
use App\Kuafu\Order\Service\OrderCouponExternalService;
use App\Kuafu\Shop\Service\DouyinLibrary\DouyinBaseService;
use App\Kuafu\Shop\Service\ShopService;
use App\Library\FeiShu\SendFs;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Redis;

class DouyinCouponBase extends DouyinBaseService implements CouponExtInterface
{
//    public const DY_KF_SELF_BUILD_DOMAIN = 'https://kuafu.douyin.com/';
    public const DY_KF_SELF_BUILD_PREFIX = 'zdy-';

    public function checkBind()
    {
        if (!empty($this->shopId)) {
            $this->getTGPoiId();
        }
    }

    /**
     * 验券准备
     *
     * @param string $couponCode // 抖音url
     * @return array
     * @throws GuzzleException
     */
    public function couponPrepare(string $couponCode): array
    {
        $this->checkBind();
        if ($this->isTestCoupon($couponCode)) {
            $couponInfo = self::couponPrepareDataDemo($couponCode);
        } elseif (strpos($couponCode, self::DY_KF_SELF_BUILD_PREFIX) !== false) {
            $couponInfo = self::buildCouponInfo($couponCode);
        } else {
            // 获取跳转 url
            if (is_numeric($couponCode)) { // 纯数字的券码
                $requestData['code'] = $couponCode;
            } elseif (self::checkDyUrl($couponCode)) { // 合法 url 券码
                $encryptedData                = self::getCouponUrlData($couponCode);
                $requestData['encryptedData'] = $encryptedData;
            } else {  // 不合法的券码
                return [
                    'status' => false,
                    'code'   => '3000001',
                    'msg'    => '二维码扫码异常，请重新配置扫码枪或联系门店运营人员.'
                ];
            }

            $couponInfo = self::couponPrepareData($requestData);

            if (!$couponInfo['status']) {
                return $couponInfo;
            }

            // 判断查询数据是否为空
            if (empty($couponInfo['oriData']['certificates'])) {
                return [
                    'status' => false,
                    'code'   => '3000001',
                    'msg'    => '二维码扫码异常，请重新配置扫码枪或联系门店运营人员'
                ];
            }

            $oriData = $couponInfo['oriData']['certificates'][0];

            // 判断券类型 type=1团餐券; type=2代金券; type=3次卡）
            $kfCouponType = OrderCouponExternalService::toggleDyCouponType($oriData['sku']['groupon_type'] ?? 0);

            $maxCount = 1;
//            $platformDiscountAmount = 0;
            $platformDiscountAmount = $oriData['amount']['platform_discount_amount'] ?? 0;
            switch ($kfCouponType) {
                case CouponExtEnum::COUPON_TYPE_TIMES_CARD:// 次卡券
                    // 获取次卡信息
                    $timeCard  = $oriData['time_card'];
                    $userPay   = OrderCouponExternalService::calcUnitVerifyPriceReverse($oriData['amount']['coupon_pay_amount'] + $platformDiscountAmount,
                        $timeCard['times_count'], $timeCard['times_used']);
                    $deduction = OrderCouponExternalService::calcUnitVerifyPriceReverse($oriData['sku']['market_price'],
                        $timeCard['times_count'], $timeCard['times_used']);
                    $maxCount  = $timeCard['times_count'] - $timeCard['times_used'];
                    break;
                case CouponExtEnum::COUPON_TYPE_MONEY:// 代金券
                case CouponExtEnum::COUPON_TYPE_PRODUCT:// 套餐券
                    $userPay = bcadd($oriData['amount']['coupon_pay_amount'],
                        $platformDiscountAmount);

                    $deduction = $oriData['sku']['market_price'];
                    break;
                case CouponExtEnum::COUPON_TYPE_GROUP_MEALS:// 团餐券
                    $userPay = bcadd($oriData['amount']['coupon_pay_amount'],
                        $platformDiscountAmount);

                    $deduction = $oriData['sku']['market_price'];
                    $maxCount  = count($couponInfo['oriData']['certificates']);
                default:
                    break;

            }

            $returnData         = CouponExtBase::formatPrepareResponseData(
                $maxCount,
                1,
                '',
                $oriData['sku']['title'],
                $couponCode,
                $kfCouponType,
                (int)$userPay,
                (int)$deduction,
                $oriData['sku']['sold_start_time'],
                $oriData['expire_time'],
                CouponExtEnum::EXT_PLATFORM_DOUYIN,
                [],
                $oriData['sku']['third_sku_id'],
                $oriData['sku']['sku_id'],
            );
            $couponInfo['data'] = $returnData;
        }

        return $couponInfo;
    }

    /**
     * 校验抖音券码
     *
     * @param string $url
     * @return bool
     */
    public static function checkDyUrl(string $url): bool
    {
        // 判断是否是 v.douyin.com 开头的
        if ((strpos($url, 'https://v.douyin.com') === 0) && checkUrl($url)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 核销券业务处理
     *
     * @param $couponCode
     * @param int $count
     * @param string $orderId
     * @return array
     * @throws CouponExtException
     * @throws GuzzleException
     */
    public function couponConsume($couponCode, int $count, string $orderId): array
    {
        $couponInfo        = self::couponPrepare($couponCode);
        $consumeCouponList = [];

        switch ($couponInfo['data']['couponType']) {
            case CouponExtEnum::COUPON_TYPE_TIMES_CARD:// 次卡券
                $consumeCoupon = $couponInfo['oriData']['certificates'][0]['encrypted_code'] ?? '';
                for ($i = 0; $i < $count; $i++) {
                    $consumeCouponList[] = $consumeCoupon;
                }
                break;

            case CouponExtEnum::COUPON_TYPE_MONEY:// 代金券
            case CouponExtEnum::COUPON_TYPE_PRODUCT:// 套餐券
            case CouponExtEnum::COUPON_TYPE_GROUP_MEALS:// 团餐券
                $consumeCoupon  = $couponInfo['oriData']['certificates'];
                $encryptedCodes = array_column($consumeCoupon, 'encrypted_code');

//                dump($encryptedCodes);
//                dd($couponInfo);

                for ($i = 0; $i < $count; $i++) {
                    $consumeCouponList[] = $encryptedCodes[$i];
                }

            default:
                break;

        }

        if ($this->isTestCoupon($couponCode)) {
            $couponConsume = self::doCouponConsumeDemo($consumeCouponList, $orderId);
        } else {
//            throw new \Exception();
            $couponConsume = self::doCouponConsume($consumeCouponList, $orderId);
        }

        // 针对不能用的券单独处理
        if (!$couponConsume['status'] && $couponConsume['code'] == 1228 && $couponConsume['msg'] == '所选门店不在商品适用门店内') {
            $shopInfo             = ShopService::getShopInfo($this->shopId);
            $couponConsume['msg'] = "此抖音券无法在当前门店（{$shopInfo->shortName}）使用，请用户尝试退券后重新购买新券";
            return $couponConsume;
        }

        // 异常返回直接返回错误
        if (!$couponConsume['status']) {
            return $couponConsume;
        }

        // 判断是否正常使用
        if (empty($couponConsume['oriData']['verify_results'])) {
            $couponConsume['msg']    = '核销失败，请联系门店运营人员核实原因1001。';
            $couponConsume['status'] = false;
            return $couponConsume;
        }

        $firstVerifyResults = current($couponConsume['oriData']['verify_results']);
        if ($firstVerifyResults['result'] != 0) {
            // 核销失败
            $couponConsume['msg']    = $firstVerifyResults['msg'] ?? '核销失败，请联系门店运营人员核实原因1002。';
            $couponConsume['status'] = false;
            return $couponConsume;
        }


        $couponInfo = $couponConsume['oriData']['verify_results'][0];

        $couponCodes = [];
        foreach ($couponConsume['oriData']['verify_results'] as $couponOne) {
            $couponCodes[] = [
                'couponCode' => $couponOne['verify_id'],
            ];
        }

        $couponConsume['data'] = [
            'couponCodes' => $couponCodes,
            'couponSid'   => $couponInfo['certificate_id'],
            'couponTitle' => '',
            'deduction'   => $couponInfo['verify_amount_info']['times_card_serial_amount']['amount']['list_market_amount'] ?? 0,
        ];

        return $couponConsume;
    }

    /**
     * 核销券
     *
     * @param $couponCode
     * @param string $orderId
     * @return array
     * @throws CouponExtException
     * @throws GuzzleException
     */
    public function doCouponConsume($couponCode, string $orderId): array
    {
        $verify_token = md5(json_encode($couponCode));
        $bizParam     = [
            'verify_token'    => $verify_token,
            'poi_id'          => $this->getTGPoiId(),
            'encrypted_codes' => $couponCode,
            'order_id'        => $orderId
        ];

        $response = $this->doCurl('/goodlife/v1/fulfilment/certificate/verify/', $bizParam, 'post');
        return self::commonReturn($response);
    }

    /**
     * 核销券
     *
     * @param $couponCode
     * @param string $orderId
     * @return array
     */
    public function doCouponConsumeDemo($couponCode, string $orderId): array
    {
        $testCouponList = self::getDyTestCoupon();

        $returnData = [
            'status' => true,
            'code'   => '0',
            'msg'    => 'success',
            'data'   => [],
        ];

        $oriData = [];

        foreach ($couponCode as $key => $item) {
            $couponInfo = $testCouponList[$item];

            $oriData['verify_results'][] = [
                'verify_id'      => $couponInfo['couponCode'],
                'account_id'     => $couponInfo['couponCode'],
                'certificate_id' => $couponInfo['couponCode'],
                'code'           => $couponInfo['couponCode'],
                'msg'            => '履约成功',
                'order_id'       => $orderId,
                'origin_code'    => $couponInfo['couponCode'],
                'result'         => 0,
            ];
        }

        $returnData['oriData']                = $oriData;
        $returnData['oriData']['error_code']  = 0;
        $returnData['oriData']['description'] = 'success';

        return $returnData;

    }


    /**
     * 验券准备
     *
     * @param array $bizParam
     * @return array
     * @throws GuzzleException
     */
    public function couponPrepareBase(array $bizParam): array
    {
        $response = $this->doCurl('/goodlife/v1/fulfilment/certificate/prepare/', $bizParam);

        return self::commonReturn($response);
    }


    /**
     * 验券准备
     *
     * @param string $code
     * @return array
     * @throws GuzzleException
     */
    public function couponPrepareCode(string $code): array
    {
        return $this->couponPrepareBase([
            'code' => $code
        ]);
    }

    /**
     * 获取抖音券的跳转码
     *
     * @param string $url
     * @return string
     */
    public function getCouponUrlData(string $url): string
    {
        $response = Http::get($url);

        $redirectUrl = $response->handlerStats()['url'] ?? '';

        if (empty($redirectUrl)) {
            SendFs::newRobot(SendFs::ROBOT_BUSINESS_WARING)
                  ->setTitleContent('抖音 预请求验券失败',
                      json_encode(['url' => $url, 'redirectUrl' => $redirectUrl], 256))
                  ->send();
            return '';
        }

        $path = explode("/", $redirectUrl);

        return $path[count($path) - 2];
    }

    /**
     * 准备券信息接口
     *
     * @param $requestData
     * @return array
     * @throws GuzzleException
     */
    public function couponPrepareData($requestData): array
    {
        $bizParam = [
            'encrypted_data' => $requestData['encryptedData'] ?? '',
            'code'           => $requestData['code'] ?? '',
        ];

        return $this->couponPrepareBase($bizParam);
    }

    /**
     * 抖音券状态信息查询
     *
     * @param string $encryptedData
     * @return array
     * @throws GuzzleException
     */
    public function couponStatus(string $encryptedData): array
    {
        $bizParam = [
            'encrypted_code' => $encryptedData
        ];

        $response = $this->doCurl('goodlife/v1/fulfilment/certificate/get/', $bizParam);

        return self::commonReturn($response);
    }

    /**
     * 撤销验券
     * @param array $couponInfo
     * @return array
     * @throws GuzzleException
     */
    public function couponCancel(array $couponInfo): array
    {
        $couponExtCode = $couponInfo['couponExtCode'];

        if ($this->isTestCoupon($couponExtCode)) {
            return [
                'status' => true
            ];
        }

        $couponExtCodeData = json_decode($couponInfo['couponExtCodeData'], true);
        //找到对应券的信息
        $verifyList = array_column($couponExtCodeData['verify_results'], null, 'verify_id');

        $verifyId      = $verifyList[$couponExtCode]['verify_id'];
        $certificateId = $verifyList[$couponExtCode]['certificate_id'];

        $bizParam = [
            'verify_id'      => $verifyId,
            'certificate_id' => $certificateId,
        ];

        $response = $this->doCurl('/goodlife/v1/fulfilment/certificate/cancel/', $bizParam, 'post');

        return self::commonReturn($response);
    }


    private function isTestCoupon(string $couponCode): bool
    {
        // 是否是测试环境
        if (!isTest()) {
            return false;
        }

        $testCouponList = self::getDyTestCoupon();

        return key_exists($couponCode, $testCouponList);
    }

    private function getDyTestCoupon()
    {
        $extTestCoupon = ConfigModel::getConfigByTypeKeyOne('posProduct', 'extTestCoupon', 10);

        if (empty($extTestCoupon) || !isJson($extTestCoupon['value'])) {
            return false;
        }

        $configList = json_decode($extTestCoupon['value'], 1)['dy'] ?? [];

        return array_column($configList, null, 'couponCode');

    }

    /**
     * 准备券信息接口 DEMO
     *
     * @param string $couponCode
     * @return array
     */
    public function couponPrepareDataDemo(string $couponCode): array
    {
        $testCouponList  = self::getDyTestCoupon();
        $couponInfo      = $testCouponList[$couponCode];
        $couponTitle     = $couponInfo['couponTitle'];
        $couponCode      = $couponInfo['couponCode'];
        $couponType      = $couponInfo['couponType'];
        $userPay         = $couponInfo['userPay'];
        $deduction       = $couponInfo['deduction'];
        $couponBeginTime = $couponInfo['couponBeginTime'];
        $couponEndTime   = $couponInfo['couponEndTime'];
        $skuId           = $couponInfo['skuId'];
        $canUseProduct   = $couponInfo['canUseProduct'];
        $count           = $couponInfo['count'] ?? 1;

        $certificates = [];
        for ($i = 0; $i < $count; $i++) {
            $certificates[] = [
                'amount'         =>
                    [
                        'coupon_pay_amount'      => 1990,
                        'list_market_amount'     => 5100,
                        'merchant_ticket_amount' => 500,
                        'original_amount'        => 2490,
                        'pay_amount'             => 1990,
                    ],
                'encrypted_code' => $couponCode . $i,
                'expire_time'    => 1692028799,
                'sku'            =>
                    [
                        'third_sku_id'    => '',
                        'title'           => $couponTitle,
                        'account_id'      => '7089001835192649766',
                        'groupon_type'    => 1,
                        'market_price'    => 5100,
                        'sku_id'          => '1771193018659895',
                        'sold_start_time' => 1689141234,
                    ],
            ];
        }

        $returnData = array(
            'status'  => true,
            'code'    => '0',
            'msg'     => 'success',
            'oriData' =>
                array(
                    'certificates' => $certificates,
                    'order_id'     => '1003748810853467454',
                    'verify_token' => '5a64af4a-2296-4f62-ab07-71207843ffad',
                    'error_code'   => 0,
                    'description'  => 'success',
                ),
        );

        $returnData['data'] = CouponExtBase::formatPrepareResponseData(
            $count,
            1,
            '',
            $couponTitle,
            $couponCode,
            $couponType,
            $userPay,
            $deduction,
            $couponBeginTime,
            $couponEndTime,
            CouponExtEnum::EXT_PLATFORM_DOUYIN,
            [],
            $canUseProduct,
            $skuId,
        );

        return $returnData;
    }

    public function buildCouponInfo(string $couponCode): array
    {
        $couponInfo = Redis::get('dy_build_code:' . $couponCode);
        $couponInfo = json_decode($couponInfo, 1);

        $kfCouponType = OrderCouponExternalService::toggleDyCouponType($couponInfo['sku_info']['groupon_type'] ?? 0);

        $maxCount               = 1;
        $platformDiscountAmount = $couponInfo['amount']['platform_ticket_amount'] ?? 0;

        switch ($kfCouponType) {
            case CouponExtEnum::COUPON_TYPE_TIMES_CARD:// 次卡券
                // 获取次卡信息
                $timeCard  = $couponInfo['times_card_info'];
                $usedTimes = $timeCard['total_times'] - $timeCard['usable_times'];
                $userPay   = OrderCouponExternalService::calcUnitVerifyPriceReverse($couponInfo['amount']['coupon_pay_amount'],
                        $timeCard['total_times'], $usedTimes) + $platformDiscountAmount;
                $deduction = OrderCouponExternalService::calcUnitVerifyPriceReverse($couponInfo['sku_info']['market_price'],
                    $timeCard['total_times'], $usedTimes);
                $maxCount  = $timeCard['usable_times'];
                break;
            case CouponExtEnum::COUPON_TYPE_MONEY:// 代金券
            case CouponExtEnum::COUPON_TYPE_PRODUCT:// 套餐券
            case CouponExtEnum::COUPON_TYPE_GROUP_MEALS:// 团餐券
            default:
                $userPay   = $couponInfo['amount']['coupon_pay_amount'] + $platformDiscountAmount;
                $deduction = $couponInfo['sku_info']['market_price'];
        }

        $couponType = $kfCouponType;
        return array(
            'status'  => true,
            'code'    => '0',
            'msg'     => 'success',
            'data'    =>
                [
                    'count'           => $maxCount,
                    'couponSid'       => '',
                    'couponTitle'     => $couponInfo['sku_info']['title'],
                    'couponCode'      => $couponCode,
                    'couponType'      => $couponType,
                    'userPay'         => $userPay,
                    'deduction'       => $deduction,
                    'couponBeginTime' => $couponInfo['start_time'],
                    'couponEndTime'   => $couponInfo['expire_time'],
                    'minConsume'      => 1,
                    'dealMenu'        => [],
                    'canUseProduct'   => $couponInfo['sku_info']['third_sku_id'] ?? '',
                    'skuId'           => $couponInfo['sku_info']['sku_id'],
                ],
            'oriData' => [
                'order_id'     => '',
                'verify_token' => '',
                'error_code'   => 0,
                'description'  => 'success',
            ],
        );
    }


    public function buildCouponConsume(array $couponPrepare, int $couponNum): array
    {
        $demoData =
            [
                'data' => [],
                'base' =>
                    array(
                        'log_id'       => '',
                        'gateway_code' => 0,
                        'gateway_msg'  => '',
                        'biz_code'     => 0,
                        'biz_msg'      => '',
                    ),
            ];

        $verify_results = [];
        for ($i = 0; $i < $couponNum; $i++) {
            $verify_results[] =
                [
                    'account_id'     => '',
                    'certificate_id' => '',
                    'code'           => $couponPrepare['couponCode'],
                    'msg'            => '验券成功',
                    'origin_code'    => '',
                    'result'         => 0,
                    'verify_id'      => '',
                ];
        }
        $demoData['data']['verify_results'] = $verify_results;

        $couponConsume = self::commonReturn($demoData);

        $couponInfo = $couponConsume['oriData']['verify_results'][0];

        $couponCodes = [];
        foreach ($couponConsume['oriData']['verify_results'] as $couponOne) {
            $couponCodes[] = [
                'couponCode' => $couponOne['code'],
            ];
        }

        $couponConsume['data'] = [
            'couponCodes' => $couponCodes,
            'couponSid'   => $couponInfo['certificate_id'],
            'couponTitle' => '',
            'deduction'   => $couponInfo['verify_amount_info']['times_card_serial_amount']['amount']['list_market_amount'] ?? 0,
        ];

        return $couponConsume;
    }

    public static function getDyWebProductInfo(string $productName)
    {

        $client  = new Client();
        $headers = [
            'authority'           => 'life.douyin.com',
            'ac-tag'              => 'ka_10h',
            'accept'              => 'application/json, text/plain, */*',
            'accept-language'     => 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-TW;q=0.6',
            'agw-js-conv'         => 'str',
            'content-type'        => 'application/json',
            'cookie'              => 's_v_web_id=verify_lk681r8l_jUvwqpm4_ZnxQ_4YrW_BESS_i4pBpxS5ssya; passport_csrf_token=8e7c491473d5808b9092391ead2652f6; passport_csrf_token_default=8e7c491473d5808b9092391ead2652f6; passport_auth_status_ls=255396da93827669287cc93a1791c78e%2C; passport_auth_status_ss_ls=255396da93827669287cc93a1791c78e%2C; sid_guard_ls=00a61b78b3a1024e0f4bb6c216947c3a%7C1689561877%7C5184002%7CFri%2C+15-Sep-2023+02%3A44%3A39+GMT; uid_tt_ls=1229da8cd8821bdb5047844e07c6169c; uid_tt_ss_ls=1229da8cd8821bdb5047844e07c6169c; sid_tt_ls=00a61b78b3a1024e0f4bb6c216947c3a; sessionid_ls=00a61b78b3a1024e0f4bb6c216947c3a; sessionid_ss_ls=00a61b78b3a1024e0f4bb6c216947c3a; sid_ucp_v1_ls=1.0.0-KDRjMDZiOGFjZjhmNWM2YzdlYTFiOTRhMzBmYzBkMTI3YzUzMDU3NmEKGgj-kcDZso2-AxCV1tKlBhjRwRIgDDgCQPEHGgJsZiIgMDBhNjFiNzhiM2ExMDI0ZTBmNGJiNmMyMTY5NDdjM2E; ssid_ucp_v1_ls=1.0.0-KDRjMDZiOGFjZjhmNWM2YzdlYTFiOTRhMzBmYzBkMTI3YzUzMDU3NmEKGgj-kcDZso2-AxCV1tKlBhjRwRIgDDgCQPEHGgJsZiIgMDBhNjFiNzhiM2ExMDI0ZTBmNGJiNmMyMTY5NDdjM2E; store-region=cn-bj; store-region-src=uid; __live_version__=%221.1.1.1623%22; live_can_add_dy_2_desktop=%220%22; odin_tt=15f70fec388957184384dee77426f006152d71303e3223a19cf65b45e914bf2ad82330cb58bf385c93c618e43d90adb592b95902447fa87c6822f664e89683e48f327bc428749838d73da0f5c38e7111; FORCE_LOGIN=%7B%22videoConsumedRemainSeconds%22%3A180%7D; msToken=VtnroWcNojk_Z54Daz7WhTPtdA5tGVjQpfZiRZUcPLmYbxYBsi8qIrbkuUComYuR5fbGY7gZ_rmSKSNwFb9rbjkUCznTlN3efWCD5M1x; csrf_session_id=7d11c91f50c372e2d2efdf19cb595379; ttwid=1%7CTlWn-uqdizglxkhzjfvnJ5AOUQ1ZjxYLxujdmIZj_60%7C1690264452%7C158bc5916b6caeee6aade284119a23fbdff653982cd915dd9d276bfdfb8ec2b3',
            'dnt'                 => '1',
            'origin'              => 'https://life.douyin.com',
            'referer'             => 'https://life.douyin.com/p/goods?groupid=1732447317648398',
            'sec-ch-ua'           => '"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
            'sec-ch-ua-mobile'    => '?0',
            'sec-ch-ua-platform'  => '"macOS"',
            'sec-fetch-dest'      => 'empty',
            'sec-fetch-mode'      => 'cors',
            'sec-fetch-site'      => 'same-origin',
            'user-agent'          => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
            'x-secsdk-csrf-token' => '000100000001dd142d279eb6a2fc0d320aacef35e60cf2423abb9d0729fbb021562d0118444a177506905ec7f381',
            'x-tt-ls-session-id'  => '5702dfbf-f539-4464-980a-d43bfe8b33f3',
            'x-tt-trace-id'       => '00-8ba26f6e18be940db4a491cb-8ba26f6e18be940d-01',
            'x-tt-trace-log'      => '01'
        ];
        $body    = '{
  "filter_product_name": "' . $productName . '",
  "exclude_poi_info": true,
  "product_type_list": [
    "1",
    "11",
    "12",
    "15"
  ],
  "filter_status": 9,
  "cursor": "0",
  "count": 10,
  "search_after": "",
  "search_param_str": "{\"SearchAllAccountPoiType\":0,\"ExpandToPoiAccount\":true,\"SearchAllAccountPoiStatus\":0,\"RelationTypes\":[1],\"SettleStatusBeforeClaim\":[],\"Selections\":[],\"TagIDList\":[],\"MainCategoryList\":{},\"SubCategoryList\":{}}",
  "permission_common_param": {
    "all_selected_params": "{\"SearchAllAccountPoiType\":0,\"ExpandToPoiAccount\":true,\"SearchAllAccountPoiStatus\":0,\"RelationTypes\":[1],\"SettleStatusBeforeClaim\":[],\"Selections\":[]}"
  }
}';
        $request = new Request('POST',
            'https://life.douyin.com/life/goods/product/list/v2?ac_app=10148&root_life_account_id=7089001835192649766',
            $headers, $body);
        $res     = $client->sendAsync($request)->wait();

        $result = json_decode($res->getBody()->getContents(), true);

        return $result['product_detail_list'];
    }
}
